<?php
/**
 * Process handler
 *
 * @author		Joachim Ruf
 * @copyright	Copyright (c) 2003-2013 Loresoft Software (http://www.loresoft.de)
 * @license		http://yapary.loresoft.de/lizenzbedingungen     New BSD License
 *
 * @see			http://www.d-mueller.de/blog/parallel-processing-in-php/
 *
 * */


Class Yapary_Process_Handler
{
	/*@var $arrConnection[Yapary_Process_Connection] */
	private $arrConnection		= array();
	private $arrResult			= array();
	private	$curlResource		= NULL;


	function __construct () {
		$this->curlResource		= curl_multi_init();
	}


	public function add (Yapary_Process_Connection $_connection) {
		$this->arrConnection[]	= $_connection;
	}


	public function addList (array $_arrConnection) {
		$this->arrConnection	= array_merge($this->arrConnection, $_arrConnection);
	}


	/**
	 * Parallel URL loading
	 * @return Array[]
	 * */
	public function run ($_maxProcess = NULL) {
		$arrResult				= array();
		$arrData				= array();

		// Prepare parallelizing
		$count					= 0;
		/* @var $oConnection Yapary_Process_Connection */
		foreach ($this->arrConnection as $key => $oConnection) {
			$element			= $oConnection->getElement();
			curl_multi_add_handle($this->curlResource, $element);

			if (is_numeric($_maxProcess) && ($key+1) >= $_maxProcess) { // Load until $_maxProcess exceeded
				break;
			}
		}

		// Load URLs
		$running				= NULL;
		do {
			curl_multi_exec($this->curlResource, $running);

			if ($count <= count($this->arrConnection)) { // reload new URLs if available
				/* @var $oConnection Yapary_Process_Connection */
				$oConnection	= next($this->arrConnection);

				if (is_object($oConnection) === true) {
					$element	= $oConnection->getElement();
					curl_multi_add_handle($this->curlResource, $element);
				}
			}
		} while ($running > 0);

		// Save data
		foreach($arrData as $key => $oConnection) {
			curl_multi_remove_handle($this->curlResource, $oConnection);
		}

		// Close and return data
		curl_multi_close($this->curlResource);
	}


}